﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace TweakSP.Web.Application
{
    public class TweakSP_ApplicationMenu : System.Web.UI.WebControls.WebControl
    {

        protected SubMenuTemplate tweakSubMenu;
        protected FeatureMenuTemplate tweakMenuTemplate;
        protected FeatureMenuTemplate tweakWebPartMenuTemplate;


        protected override void CreateChildControls()
        {
            tweakSubMenu = new SubMenuTemplate();
            tweakSubMenu.Text = "TweakSP";
            tweakSubMenu.Description = "TweakSP Application Actions";
            tweakSubMenu.ImageUrl = "/_layouts/images/lg_ICASCX.gif";
            this.Controls.Add(tweakSubMenu);

            // Using a similar approach to the SiteActions Menu <SharePoint:FeatureMenuTemplate runat="server" FeatureScope="Site" Location="Microsoft.SharePoint.StandardMenu" GroupId="SiteActions" UseShortId="true">
            tweakMenuTemplate = new FeatureMenuTemplate();
            tweakMenuTemplate.FeatureScope = "Site";
            tweakMenuTemplate.Location = "Microsoft.SharePoint.TweakMenu";
            tweakMenuTemplate.GroupId = "Tweak";
            this.Controls.Add(tweakMenuTemplate);


            tweakWebPartMenuTemplate = new FeatureMenuTemplate();
            tweakWebPartMenuTemplate.FeatureScope = "Site";
            tweakWebPartMenuTemplate.Location = "Microsoft.SharePoint.TweakMenu";
            tweakWebPartMenuTemplate.GroupId = "WebParts";
            this.Controls.Add(tweakWebPartMenuTemplate);
        }


        /// <summary>
        /// Our tweakMenuTemplate is being added to the SiteActions menu by default so we have to move all of the individual MenuItemTemplates over to the correct SubMenu
        /// </summary>
        protected override void OnPreRender(EventArgs e)
        {
            try
            {
                while (tweakMenuTemplate.Controls.Count > 0)
                {
                    Control menuItem = tweakMenuTemplate.Controls[0];
                    tweakSubMenu.Controls.Add(menuItem);
                }

                // Seperator
                MenuSeparatorTemplate subMenuSep = new MenuSeparatorTemplate();
                tweakSubMenu.Controls.Add(subMenuSep);

                while (tweakWebPartMenuTemplate.Controls.Count > 0)
                {
                    Control menuItem = tweakWebPartMenuTemplate.Controls[0];
                    tweakSubMenu.Controls.Add(menuItem);
                }
                
            }
            catch
            {
                // Add some error handling here maybe?
            }

            base.OnPreRender(e);
        }

    }
}
